﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using PluginInterface;
using SdmxMl.Helper;

namespace GeoPlugIn
{
    public partial class UcGeo : UserControl, IPlugin
    {

        #region IPlugin Members

        /// <summary>Event is part of interface but not used </summary>
        public event PluginEvent PluginEventExposed
        {
            add { }
            remove { }
        }

        public void Init(System.Xml.XmlDocument xDoc, object obExtend)
        {
        }

        public UserControl VisualComponent()
        {
            return this;
        }

        public bool RequiresInit
        {
            get { return false; }
        }

        #endregion



        #region Domains enumeration

        /// <summary>Working Domain enumeration</summary>
        enum ConvertModule
        {
            HGDE,
            StatesTerritories,
        }
        #endregion

        #region Internal Members

        private ConvertModule module;
        private IReader reader;
        private TextProvider msgProvider;

        #endregion

        #region Constructor

        public UcGeo()
        {
            InitializeComponent();


            // Set default conversion domain module
            SetModule(ConvertModule.HGDE);
        }
        #endregion

        #region Domain Selection

        /// <summary>Menu Event, Selection of domain 'Historized municipalities' </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void hGDEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetModule(ConvertModule.HGDE);
        }

        /// <summary>Menu Event, Selection of domain 'States & Territories' </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void statesAndTerritoriesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetModule(ConvertModule.StatesTerritories);

        }

        /// <summary> GUI Update according to domain selected </summary>
        /// <param name="m">Selected domain module</param>
        private void SetModule(ConvertModule m)
        {
            module = m;

            // Clear Edit fields
            textBoxDate.Text = string.Empty;
            textBoxDest.Text = string.Empty;
            textBoxSource.Text = string.Empty;
            textBoxInfo.Text = string.Empty;
            numTextBoxVersion.Text = string.Empty;

            // Set specific
            if (module == ConvertModule.StatesTerritories)
            {
                labelTitle.Text = "States and Territories - SDMX Converter";
                numTextBoxVersion.Enabled = true;
                hGDEToolStripMenuItem.Checked = false;
                statesAndTerritoriesToolStripMenuItem.Checked = true;
                openFileDialog.FilterIndex = 1;
            }
            else if (module == ConvertModule.HGDE)
            {
                labelTitle.Text = "Swiss communes history  - SDMX Converter";
                numTextBoxVersion.Enabled = true;
                numTextBoxVersion.Text = DateTime.Now.Year.ToString() + ".1";
                hGDEToolStripMenuItem.Checked = true;
                statesAndTerritoriesToolStripMenuItem.Checked = false;
                openFileDialog.FilterIndex = 2;
            }

            UpdateMenu();

        }

        /// <summary>Updates menu and buttons according to current context </summary>
        private void UpdateMenu()
        {
            buttonConvert.Enabled = runConversionToolStripMenuItem.Enabled =
                textBoxSource.Text.Length > 0;
            //file destination is now optional
             //   &&  textBoxDest.Text.Length > 0; 
        }

        #endregion

        #region Source documents definition & control 

        /// <summary> 
        /// Open source file(s) required for SDMX generation. Read and pre-check 
        /// source document(s).
        /// </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void openExcelSourceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                // Raise file dialog
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string filepath = openFileDialog.FileName;
                    
                    // Create reader according to selected domain
                    if (module == ConvertModule.HGDE)
                        reader = new HgdeHistory(filepath);
                    else
                        reader = new ExcelSTreader(filepath);

                    // Pre conditions checking
                    if (reader.ValidatePreConditions())
                    {
                        textBoxInfo.Text = reader.Diagnostic;
                        throw new ApplicationException(reader.Diagnostic);
                    }

                    // Refresh User GUI
                    textBoxSource.Text = filepath;
                    textBoxDate.Text = reader.VersionDate;
                    numTextBoxVersion.Text = reader.VersionSdmx;
                    if (reader.VersionSdmx.Length == 0)
                        textBoxInfo.Text = "SDMX Version not detected. Please fill version manually.";

                    UpdateMenu();

                    // Load text provider
                    if (msgProvider == null)
                        msgProvider = new TextProvider(System.Windows.Forms.Application.StartupPath + "\\CH1_SMS+CS_GEWO_LOADER_MSG+1.0.xml");

                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary> Raise dialog for defining SDMX files destination folder </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void destinationFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult res = folderBrowserDialog1.ShowDialog();
                if (res == DialogResult.OK)
                {
                    textBoxDest.Text = folderBrowserDialog1.SelectedPath;

                    UpdateMenu();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        #endregion

        #region Convert to SDMX (event request)

        /// <summary>Convert source document of selected domain to SDMX artefacts </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void convertToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Verify SDMX artefact version is defined
            if (numTextBoxVersion.Text.Length == 0)
            {
                MessageBox.Show(this, "Please enter SDMX version number, it was not detected on Excel source.",
                    "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                try
                {
                    using (new SdmxMl.Helper.CWaitCursor())
                    {
                        // Convert according to selected domain
                        if (module == ConvertModule.HGDE)
                        {
                            // Load CSV support
                            SdmxHgde hgde = new SdmxHgde(reader, msgProvider);
                            ((HgdeHistory)reader).VersionSdmx = numTextBoxVersion.Text;
                            textBoxInfo.Text = "Creating Cantons..." + Environment.NewLine;
                            hgde.ConvertCanton(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating District..." + Environment.NewLine;
                            hgde.ConvertDistrict(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating Communes..." + Environment.NewLine;
                            this.Refresh();
                            hgde.ConvertCommunes(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating Hierarchy..." + Environment.NewLine;
                            this.Refresh();
                            hgde.CreateHierarchy(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating Snapshot..." + Environment.NewLine;
                            this.Refresh();
                            hgde.CreateSnapShot(textBoxDest.Text);
                        }
                        else
                        {
                            // No more needed as long as no changes
                            // textBoxInfo.Text = "Creating Specification Concepts..." + Environment.NewLine;
                            // SdmxSpec spec = new SdmxSpec(reader);
                            // spec.Convert(textBoxDest.Text);
                            // textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating Codelist for Territories..." + Environment.NewLine;
                            SdmxStateTerritory state = new SdmxStateTerritory(reader,
                                numTextBoxVersion.Text, msgProvider);
                            state.CreateCodeList(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating Hierarchy for Territories..." + Environment.NewLine;
                            state.CreateHierarchy(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating SnapShot States and Territories..." + Environment.NewLine;
                            state.CreateSnapshotGeo(textBoxDest.Text);
                            textBoxInfo.Text += "OK." + Environment.NewLine;

                            textBoxInfo.Text += "Creating SnapShot States Polit." + Environment.NewLine;
                            state.CreateSnapshotStates(textBoxDest.Text);
                        }
                        textBoxInfo.Text += "OK." + Environment.NewLine + "All Done.";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        #endregion

        #region Misc Menu Events

        /// <summary> Menu About event </summary>
        /// <param name="sender"></param> <param name="e"></param>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBoxMain ab = new AboutBoxMain();
            ab.ShowDialog(this);
        }

        #endregion

    }
    
}
